package com.baihuabooks.scoresys.common;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.*;

/**
 * Created by Thinkpad on 2016/5/17 0017.
 */
public class DBUtil {

    private static final DBUtil instance = new DBUtil();

    public static DBUtil getInstance() {
        return instance;
    }

    private DBUtil() {
    }

    private volatile ComboPooledDataSource dataSource;
    private String driver;
    private String url;

    public void destroy() {
        try {
            DriverManager.deregisterDriver(DriverManager.getDriver(url));
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.dataSource.close();
        }

    }

    public void init() throws PropertyVetoException {
        if (dataSource != null) {
            return;
        }

        synchronized (this) {
            if (dataSource != null) {
                return;
            }

            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setMaxPoolSize(50);
            ds.setMinPoolSize(2);
            ds.setInitialPoolSize(2);


            driver = Config.get("db.driver");
            url = Config.get("db.url");
            String username = Config.get("db.username");
            String password = Config.get("db.password");

            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);

            dataSource = ds;
        }
    }

    public Connection getConnection() throws SQLException {
        return this.dataSource.getConnection();
    }

    public static void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }

    public static void close(Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
            }
        }
    }


    public static void close(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
            }
        }
    }

    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        close(rs);
        close(stmt);
        close(conn);
    }

    public static void close(Statement stmt, Connection conn) {
        close(stmt);
        close(conn);
    }

}
